import XLSX from 'xlsx'

/**
* 验证电话号码格式,返回boolean
* @param {String} num 电话号
*/
export const validPhone = (num) => {
  return (/^1[3456789]\d{9}$/.test(num))
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
* 格式化日期,返回string
*/
export function formatDate () {
  Date.prototype.format = function(fmt) { 
    var o = { 
      "M+" : this.getMonth()+1,                 //月份 
      "d+" : this.getDate(),                    //日 
      "h+" : this.getHours(),                   //小时 
      "m+" : this.getMinutes(),                 //分 
      "s+" : this.getSeconds(),                 //秒 
      "q+" : Math.floor((this.getMonth()+3)/3), //季度 
      "S"  : this.getMilliseconds()             //毫秒 
    } 
    if (/(y+)/.test(fmt)) {
      fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length))
    }
    for(var k in o) {
      if (new RegExp("("+ k +")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)))
      }
    }
   return fmt
  }
}

/**
 * 导出数据（兼容ie浏览器）
 * @param {string, string} fileName 
 */
export function exportSearchList(dowLoadFileName, result) {
  const blob = new Blob([result])
  const fileName = dowLoadFileName + '.xls'
  // 判断浏览器
  var brower = ''
  if (navigator.userAgent.indexOf('Edge') > -1) {
    brower = 'Edge'
  }
  if ('download' in document.createElement('a')) {
    // 非IE下载
    if (brower == 'Edge') {
      navigator.msSaveBlob(blob, fileName)
      return
    }
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    // 释放URL 对象
    document.body.removeChild(elink)
  } else {
    // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}

/**
 * 前端导出数据
 * @param {Array, Array, String}
 */

export function outputFile (data,header,name) {
  const ws = XLSX.utils.json_to_sheet(data,header)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb,ws,name)
  XLSX.writeFile(wb,name + '.xlsx')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

/*
* 验证账号密码格式,返回boolean
* @param {String} account 账号
*/
export const validAccount = (account) => {
  return (/^[A-Za-z0-9_]+$/.test(account))
}
